/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.gui.widgets.visual.modeldriven;

import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.jgrapht.DirectedGraph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.DefaultEdge;

import dgbgui.gui.widgets.Widget;
import dgbgui.gui.widgets.WidgetFactory;
import dgbgui.gui.widgets.WidgetStore;
import dgbgui.gui.widgets.layouts.HierarchicalTreeLayout;
import dgbgui.gui.widgets.visual.EdgeWidget;
import dgbgui.gui.widgets.visual.IncludeExcludeTermWidget;
import dgbgui.modeldocument.DGBModel;
import dgbgui.modeldocument.ModelDrivenEdge;
import dgbgui.modeldocument.ModelDrivenWorkspace;
import dgbgui.modeldocument.Query;
import dgbgui.modeldocument.primitives.Concept;
import dgbgui.modeldocument.primitives.DefaultEdgeWithWidget;
import edu.umd.cs.piccolo.PNode;

@SuppressWarnings("serial")
public class ModelGraphWidget extends Widget {

    
    public ModelGraphWidget(PNode parent, DGBModel model) {
        super(parent);
        
        m_layout = new HierarchicalTreeLayout(this, 5.0, 40.0);
        
        // Temporary mapping between primitives and visula representation
        Map<Concept,Widget> toVisualMap = new HashMap<Concept,Widget>();
        
        // Create a widget for each vertex, add it to the widget 
        // graph and also the temporary map
        for ( Concept concept : model.getConcepts() ) {
            Query query = ModelDrivenWorkspace.getInstance().getQuery(concept);
            boolean isTarget = (ModelDrivenWorkspace.getInstance().getTarget() == concept);
            ModelDrivenConceptWidget vertexWidget = WidgetFactory.createModelDrivenWidget(m_layout,concept,query,isTarget);
            m_widgetGraph.addVertex(vertexWidget);
            toVisualMap.put(concept,vertexWidget);

        }
        
        // Create the edges
        for ( ModelDrivenEdge edge : model.getEdges() ) {
                
            Concept source = model.getEdgeSource(edge);
            Concept target = model.getEdgeTarget(edge);
            
            // Edge widget, no arrow at this point
            EdgeWidget edgeWidget = new EdgeWidget(
                    m_layout,
                    "",0.0);
            edgeWidget.setStrokeColor(Color.gray);


            m_widgetGraph.addEdge(
                    toVisualMap.get(source), 
                    toVisualMap.get(target),
                    new DefaultEdgeWithWidget(edgeWidget));
        }
        
        // Update the connected concepts
        updateIncluded();
        
        m_layout.setGraph(m_widgetGraph);
    }
    
    public void updateIncluded() {
        // Update the connected concepts
        Set<DefaultEdge> connections = ModelDrivenWorkspace.getInstance().getIncludeEdges();
        for ( DefaultEdge edge : connections ) {
            Concept source = ModelDrivenWorkspace.getInstance().getIncludeSource(edge);
            Concept target = ModelDrivenWorkspace.getInstance().getIncludeTarget(edge);
            
            ModelDrivenConceptWidget sourceWidget = WidgetStore.getInstance().getModelDrivenWidget(source);
            ModelDrivenConceptWidget targetWidget = WidgetStore.getInstance().getModelDrivenWidget(target);
            
            DefaultEdgeWithWidget edgeWidget = m_widgetGraph.getEdge(sourceWidget, targetWidget);
            if ( edgeWidget != null ) {
                edgeWidget.getWidget().setArrow();
                edgeWidget.getWidget().setStrokeColor(Color.black);
            } else {
                edgeWidget = m_widgetGraph.getEdge(targetWidget,sourceWidget);
                if ( edgeWidget != null ) {
                    edgeWidget.getWidget().setReverseArrow();
                    edgeWidget.getWidget().setStrokeColor(Color.black);
                }
            }
        }
        
    }
    
    private enum IncludeExclude { INCLUDE, EXCLUDE };
    
    private void showIncludableExcludable(Concept source, Set<Concept> connected,IncludeExclude inOrEx) {
        ModelDrivenConceptWidget sourceVertex = WidgetStore.getInstance().getModelDrivenWidget(source);
        for ( Concept target : connected ) {
            // Try the default direction
            ModelDrivenConceptWidget targetVertex = WidgetStore.getInstance().getModelDrivenWidget(target);
            DefaultEdgeWithWidget edge = m_widgetGraph.getEdge(sourceVertex, targetVertex);
            if ( edge != null ) {
                edge.getWidget().setReverseArrow();
                if ( inOrEx == IncludeExclude.INCLUDE ) {
                    edge.getWidget().setStrokeColor(Color.green);
                } else {
                    edge.getWidget().setStrokeColor(Color.red);
                }

                // The include term widget
                IncludeExcludeTermWidget w = new IncludeExcludeTermWidget(edge.getWidget().getParent(),target,inOrEx == IncludeExclude.INCLUDE);
                w.setOffset(
                        edge.getWidget().getFullBounds().getCenterX() - w.getFullBounds().getWidth()/2,
                        edge.getWidget().getFullBounds().getCenterY() - w.getFullBounds().getHeight()/2);
                m_includeWidgetMap.put(target,w);
                
            } else {
                // Try the reverse direction
                edge = m_widgetGraph.getEdge(targetVertex, sourceVertex);
                if ( edge != null ) {
                    edge.getWidget().setArrow();
                    
                    if ( inOrEx == IncludeExclude.INCLUDE ) {
                        edge.getWidget().setStrokeColor(Color.green);
                    } else {
                        edge.getWidget().setStrokeColor(Color.red);
                    }
                    
                    // The include term widget
                    IncludeExcludeTermWidget w = new IncludeExcludeTermWidget(edge.getWidget().getParent(),target,inOrEx == IncludeExclude.INCLUDE);
                    w.setOffset(
                            edge.getWidget().getFullBounds().getCenterX() - w.getFullBounds().getWidth()/2,
                            edge.getWidget().getFullBounds().getCenterY() - w.getFullBounds().getHeight()/2);
                    m_includeWidgetMap.put(target,w);
                }
            }

            // Indicate the selectable concept
            if ( inOrEx == IncludeExclude.INCLUDE ) {
                targetVertex.showSelectable(Color.green);
            } else {
                targetVertex.showSelectable(Color.red);
            }
        }

    }
    
    /**
     * Show the includable terms
     * @param source
     * @param connected
     */
    public void showIncludable(Concept source, Set<Concept> connected) {
        showIncludableExcludable(source,connected,IncludeExclude.INCLUDE);
    }
    
    /**
     * Show the excludable terms
     * @param source
     * @param connected
     */
    public void showExcludable(Concept source, Set<Concept> connected) { 
        showIncludableExcludable(source,connected,IncludeExclude.EXCLUDE);
    }
    
    public void restoreIncludable(Concept source, Set<Concept> connected) {
        ModelDrivenConceptWidget sourceVertex = WidgetStore.getInstance().getModelDrivenWidget(source);
        for ( Concept target : connected ) { 
            
            ModelDrivenConceptWidget targetVertex = WidgetStore.getInstance().getModelDrivenWidget(target);
            DefaultEdgeWithWidget edge = m_widgetGraph.getEdge(sourceVertex, targetVertex);
            if ( edge != null ) {
                edge.getWidget().removeArrow();
                edge.getWidget().setStrokeColor(Color.gray);
            } else {
                // Try the reverse direction
                edge = m_widgetGraph.getEdge(targetVertex, sourceVertex);
                if ( edge != null ) {
                    edge.getWidget().removeArrow();
                    edge.getWidget().setStrokeColor(Color.gray);
                }
            }
            
            // Restore the selectable indication
            targetVertex.restoreSelectable();
        }
        
        // Remove all the includable widgets
        for ( IncludeExcludeTermWidget w : m_includeWidgetMap.values() ) {
            w.removeFromParent();
        }
        m_includeWidgetMap.clear();
        
        // Update the display of the currently included terms
        updateIncluded();
    }
    
    Map<Concept,IncludeExcludeTermWidget> m_includeWidgetMap = new HashMap<Concept,IncludeExcludeTermWidget>();
    
    HierarchicalTreeLayout m_layout;
    DirectedGraph<Widget,DefaultEdgeWithWidget> m_widgetGraph 
        = new DefaultDirectedGraph<Widget,DefaultEdgeWithWidget>(DefaultEdgeWithWidget.class);

}
